package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.dao.IFrontOrderDao;
import com.xteam.ecsystem.entities.BaseCartInfo;
import com.xteam.ecsystem.entities.BaseDeliveryMode;
import com.xteam.ecsystem.entities.BaseDistributeRegion;
import com.xteam.ecsystem.entities.BaseModePayment;
import com.xteam.ecsystem.entities.BaseOrderGoods;
import com.xteam.ecsystem.entities.BaseOrderInfo;
import com.xteam.ecsystem.utils.PageCenterStation;
import com.xteam.ecsystem.utils.StringUtil;

@Repository
@SuppressWarnings("unchecked")
/**
 * 
 * 前端订单实现类
 * @author ls
 *
 */
public class FrontOrderDaoImpl extends DDLPrefix implements IFrontOrderDao {
	
	@Autowired
	private BaseDaoImpl baseDao;
	
	/**
	 * 根据用户ID获取订单列表
	 */
	public PageCenterStation<?> getOrderListByMemberId(int pageIndex, int pageSize, String memberId) {
		if(memberId != null){
			List list = new ArrayList();
			
			String hql = SQL_FROM  + BaseOrderInfo.REF + SQL_WHERE + " boiMember = ? ";
			String countHQL = SQL_SELECT + " count(*) " + SQL_FROM
					+ BaseOrderInfo.REF + SQL_WHERE + " boiMember = ? ";
			list.add(memberId);
			
			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao
 					 .queryList(countHQL, hql, list.toArray(), (pageIndex - 1) * pageSize, pageSize);
			
			return p;
		}
		
		return null;
	}
	
	/**
	 * 获取订单中存在变化的商品信息
	 */
	@Override
	public List<?> getPriceChange(String userId) {
		if(userId != null){
			List list = new ArrayList();
			
			list = baseDao.queryListByProcedure("price_change_info", new Object[]{ userId });
			
			if(list.size() > 0){
				return list;
			}else {
				return null;
			}
		}
		
		return null;
	}
	
	/**
	 * 保存订单信息，将购物车中商品移入订购商品表
	 * @see com.xteam.ecsystem.dao.IFrontOrderDao#saveOrderInfo(com.xteam.ecsystem.entities.BaseOrderInfo)
	 */
	public BaseOrderInfo saveOrderInfo(BaseOrderInfo boi) {
		try {
			baseDao.save(boi);
			return boi;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public void saveOrderGoods(List<BaseOrderGoods> list){
		try {
			this.baseDao.batchSave(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void deleteCartGoods(List<BaseCartInfo> list){
		try {
			this.baseDao.deleteAll(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<?> getPostAgeList() {
		try {
			List list = baseDao.findAll(BaseDeliveryMode.class);
			return list;
		} catch (Exception e) {
			return null;
		}
	}
	
	public void saveCancelOrder(String orderId){
		try {
			BaseOrderInfo orderInfo = (BaseOrderInfo) this.baseDao.get(BaseOrderInfo.class, orderId);
			
			if(orderInfo != null){
				orderInfo.setBoiOrder(2);
				orderInfo.setBoiIsrefund(1);
				orderInfo.setBoiCreason("前端用户取消订单");
				
				this.baseDao.update(orderInfo);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public List<?> getMergeOrders(String userId) {
		try {
			String hql = SQL_FROM + BaseOrderInfo.REF + SQL_WHERE + "boiOrder" + SQL_IN + "(0, 1)"
					+ SQL_AND + "boiPay" + SQL_IN + "(0, 1)" + SQL_AND + "boiShip" + SQL_IN + "(0, 1, 2)"
					+ SQL_AND + "boiMember = ?";
			
			List orders = this.baseDao.find(hql, new Object[]{userId});
			
			if(orders != null && orders.size() > 0){
				return orders;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 根据订单编号获得订单信息
	 * @author liuzhi Mar 29, 2013
	 * @param orderId
	 * @return
	 */
	public BaseOrderInfo getOrderInfo(String orderId){
		try {
			String hql = SQL_FROM + BaseOrderInfo.REF + SQL_WHERE + "boiId = ?";
			
			return (BaseOrderInfo)this.baseDao.findObject(hql, new Object[]{orderId});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public List<?> getOrderGoods(String orderId){
		try {
			String hql = SQL_FROM + BaseOrderGoods.REF + SQL_WHERE + "bogOid = ?";
			
			List orderGoodsList = this.baseDao.find(hql, new Object[]{orderId});
			
			if(orderGoodsList != null && orderGoodsList.size() > 0){
				return orderGoodsList;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public boolean saveMergeOrders(BaseOrderInfo mainOrderInfo, BaseOrderInfo fellowOrderInfo){
		try {
			double mainGpay = mainOrderInfo.getBoiGpay();
			double fellowGpay = fellowOrderInfo.getBoiGpay();
			
			// 1、累计商品总额
			double newGpay = mainGpay + fellowGpay;
			// 2、累计订单总额
			double newSpay = newGpay;
			
			if(newGpay < 59){
				newSpay = newGpay + mainOrderInfo.getBoiSpay();
			}
			
			
			
			List<BaseOrderGoods> sameList = new ArrayList<BaseOrderGoods>();
			List<BaseOrderGoods> unsameList = new ArrayList<BaseOrderGoods>();
			List<BaseOrderGoods> mainOGList = (List<BaseOrderGoods>)getOrderGoods(mainOrderInfo.getBoiId());
			List<BaseOrderGoods> fellowOGList = (List<BaseOrderGoods>)getOrderGoods(fellowOrderInfo.getBoiId());
			
			if(mainOGList == null || mainOGList.isEmpty()) return false;
			if(fellowOGList == null || fellowOGList.isEmpty()) return false;
			
			// 3、复制商品列表至主订单
			for (BaseOrderGoods fellowOG : fellowOGList) {
				boolean isFound = false;
				
				for (BaseOrderGoods mainOG : mainOGList) {
					// 3.1 复制主订单中存在的商品
					if((mainOG.getBogGid()).equals(fellowOG.getBogGid()) 
							&& (mainOG.getBogAttribute()).equals(fellowOG.getBogAttribute())){
						mainOG.setBogAttprice(mainOG.getBogAttprice() + fellowOG.getBogAttprice());
						mainOG.setBogNumber(mainOG.getBogNumber() + fellowOG.getBogNumber());
						mainOG.setBogTotal(mainOG.getBogTotal() + fellowOG.getBogTotal());
						
						sameList.add(mainOG);
						isFound = true;
						break;
					}
				}
				
				if (isFound) continue;
				
				// 3.2 复制首次出现的商品
				BaseOrderGoods newOG = new BaseOrderGoods();
				newOG.setBogOid(mainOrderInfo.getBoiId());
				newOG.setBogGid(fellowOG.getBogGid());
				newOG.setBogName(fellowOG.getBogName());
				newOG.setBogMarket(fellowOG.getBogMarket());
				newOG.setBogPrice(fellowOG.getBogPrice());
				newOG.setBogAttribute(fellowOG.getBogAttribute());
				newOG.setBogAttprice(fellowOG.getBogAttprice());
				newOG.setBogNumber(fellowOG.getBogNumber());
				newOG.setBogTotal(fellowOG.getBogTotal());
				
				unsameList.add(newOG);
			}
			
			// 4、保存合并后的商品订购列表
			this.baseDao.batchUpdate(sameList.toArray());
			this.baseDao.batchSave(unsameList.toArray());
			
			// 5、保存合并后的订单表
			mainOrderInfo.setBoiGpay(newGpay);
			mainOrderInfo.setBoiTpay(newSpay);
			
			this.baseDao.update(mainOrderInfo);
			
			// 6、删除从订单及从订单中订购的商品
			this.baseDao.delete(fellowOrderInfo);
			this.baseDao.deleteAll(fellowOGList);
			
			return true;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}

	public List<?> getPayModeList(int type) {
		try {
			String hql = SQL_FROM + BaseModePayment.REF + " where bmpType = ? order by bmpType";
			List list = baseDao.find(hql,new Object[]{ type });
			if(list.size() > 0 ){
				return list;
			}else{
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public boolean isCashOnDelivery(String braDistrict) {
		try {
			String hql = SQL_FROM + BaseDistributeRegion.REF + SQL_WHERE + "bdrId = ? and bdrState = 1";
			BaseDistributeRegion bdb = (BaseDistributeRegion) baseDao.findObject(hql, new Object[]{ braDistrict });
			if(bdb.getBdrIscod() == 1){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public BaseModePayment getPayModeById(String id) {
		try {
			String hql = SQL_FROM + BaseModePayment.REF + SQL_WHERE + " bmpId = ?";
			BaseModePayment bmp = (BaseModePayment) baseDao.findObject(hql, new Object[]{ id });
			return bmp;
		} catch (Exception e) {
			return null;
		}
	}
	
	public void saveOrderConsignee(BaseOrderInfo boiObj){
		try {
			if(StringUtil.isNotNullOrEmpty(boiObj) && StringUtil.isNotNullOrEmpty(boiObj.getBoiId())){
				this.baseDao.update(boiObj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public BaseOrderInfo getOrderByBoiOsn(String boiOsn){
		try {
			String hql = SQL_FROM + BaseOrderInfo.REF + SQL_WHERE + "boiOsn = ?";
			return (BaseOrderInfo)this.baseDao.findObject(hql, new Object[]{boiOsn});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public String getUserCoupons(String userId, String goodsTotal){
		try {
			if (StringUtil.isNotNullOrEmpty(userId)) {
				List coupons = this.baseDao.queryListByProcedure("query_usable_coupon", 
						new Object[]{userId, Double.parseDouble(goodsTotal)});
				if (coupons != null && !coupons.isEmpty()) {
					return JSONArray.fromObject(coupons).toString();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
}
